// import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';
// import 'dart:convert';

// class PointInfoDialog extends StatelessWidget {
//   final dynamic content;
//   final String patrolMark;

//   const PointInfoDialog({
//     Key? key,
//     required this.content,
//     required this.patrolMark,
//   }) : super(key: key);

//   @override
//   Widget build(BuildContext context) {
//     if (content == null) {
//       return AlertDialog(
//         title: const Text('提示'),
//         content: const Text('该巡检点暂未分配任务'),
//         actions: [
//           TextButton(
//             onPressed: () => Navigator.of(context).pop(),
//             child: const Text('确定'),
//           ),
//         ],
//       );
//     }
//     return Dialog(
//       insetPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 40),
//       shape: RoundedRectangleBorder(
//         borderRadius: BorderRadius.circular(16),
//       ),
//       elevation: 10,
//       child: ConstrainedBox(
//         constraints: BoxConstraints(
//           maxHeight: MediaQuery.of(context).size.height * 0.8,
//         ),
//         child: Container(
//           padding: EdgeInsets.all(20),
//           decoration: BoxDecoration(
//             color: Colors.white,
//             borderRadius: BorderRadius.circular(16),
//           ),
//           child: Column(
//             mainAxisSize: MainAxisSize.min,
//             crossAxisAlignment: CrossAxisAlignment.stretch,
//             children: [
//               // 标题和关闭按钮
//               Row(
//                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                 children: [
//                   Text(
//                     '巡检点详情',
//                     style: TextStyle(
//                       fontSize: 18,
//                       fontWeight: FontWeight.bold,
//                       color: Colors.blue[800],
//                     ),
//                   ),
//                   IconButton(
//                     icon: Icon(Icons.close, color: Colors.grey),
//                     onPressed: () => Navigator.of(context).pop(),
//                   ),
//                 ],
//               ),
//               Divider(height: 20, thickness: 1),
//               SizedBox(height: 10),

//               // 可滚动的内容区域
//               Expanded(
//                 child: SingleChildScrollView(
//                   child: Column(
//                     mainAxisSize: MainAxisSize.min,
//                     crossAxisAlignment: CrossAxisAlignment.stretch,
//                     children: [
//                       // 根据 patrolMark 显示不同内容
//                       if (patrolMark == '1') _buildMark1Content(), //已巡
//                       if (patrolMark == '2') _buildMark2Content(), //未巡检
//                       if (patrolMark == '4') _buildMark4Content(), //异常
//                     ],
//                   ),
//                 ),
//               ),
//             ],
//           ),
//         ),
//       ),
//     );
//   }

//   Widget _buildMark1Content() {
//     Map<String, dynamic>? patrolContents;
//     try {
//       if (content['patrolContents'] != null) {
//         patrolContents =
//             Map<String, dynamic>.from(json.decode(content['patrolContents']));
//       }
//     } catch (e) {
//       print('解析 patrolContents 失败: $e');
//     }

//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.stretch,
//       children: [
//         _buildInfoRow('巡检状态', _getPatrolMarkText(content['patrolMark'])),
//         _buildInfoRow('巡查状态', _getPatrolStatusText(content['patrolStatus'])),
//         _buildInfoRow('实际巡查时间', content['patrolTime'] ?? '暂无'),
//         _buildInfoRow('巡检任务名称', content['patrolSchemeName'] ?? '暂无'),
//         _buildInfoRow('任务开始日期', content['patrolStartData'] ?? '暂无'),
//         _buildInfoRow('任务结束日期', content['patrolEndData'] ?? '暂无'),
//         _buildInfoRow('巡检项名称', content['patrolItemName'] ?? '暂无'),
//         _buildInfoRow('实际巡检人', content['patrolUserName'] ?? '暂无实际巡检人'),
//         SizedBox(height: 10),
//         Text('巡检内容:',
//             style: TextStyle(
//               fontWeight: FontWeight.bold,
//               fontSize: 16,
//               color: Colors.blue[800],
//             )),
//         SizedBox(height: 8),
//         if (patrolContents != null)
//           Container(
//             decoration: BoxDecoration(
//               border: Border.all(color: Colors.grey[300]!),
//               borderRadius: BorderRadius.circular(8),
//             ),
//             child: ListView.separated(
//               physics: NeverScrollableScrollPhysics(),
//               shrinkWrap: true,
//               itemCount: patrolContents.length,
//               separatorBuilder: (context, index) =>
//                   Divider(height: 1, color: Colors.grey[200]),
//               itemBuilder: (context, index) {
//                 final entry = patrolContents!.entries.elementAt(index);
//                 return _buildInspectionItem(
//                   entry.key,
//                   entry.value,
//                   isEditable: false,
//                 );
//               },
//             ),
//           )
//         else
//           Text('暂无巡检内容', style: TextStyle(color: Colors.grey)),
//       ],
//     );
//   }

//   Widget _buildMark2Content() {
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.stretch,
//       children: [
//         _buildInfoRow('巡检状态', _getPatrolMarkText(content['patrolMark'])),
//         _buildInfoRow('巡检任务名称', content['patrolSchemeName'] ?? '暂无'),
//         _buildInfoRow('任务开始日期', content['patrolStartData'] ?? '暂无'),
//         _buildInfoRow('任务结束日期', content['patrolEndData'] ?? '暂无'),
//         _buildInfoRow('巡检项名称', content['patrolItemName'] ?? '暂无'),
//         _buildInfoRow(
//             '巡检人',
//             (content['userName'] as List<dynamic>?)
//                     ?.map((e) => e['nickName'])
//                     .join('、') ??
//                 '暂无'),
//         _buildInfoRow('巡检内容', content['patrolContents'] ?? '暂无'),
//       ],
//     );
//   }

//   Widget _buildMark4Content() {
//     Map<String, dynamic>? spare3;
//     try {
//       if (content['spare3'] != null) {
//         spare3 = Map<String, dynamic>.from(json.decode(content['spare3']));
//       }
//     } catch (e) {
//       print('解析 patrolContents 失败: $e');
//     }

//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.stretch,
//       children: [
//         _buildInfoRow('巡检时间', content['createTime'] ?? '暂无'),
//         _buildInfoRow('人员', content['registerUser'] ?? '暂无'),
//         _buildInfoRow('描述', content['remark'] ?? '暂无描述'),
//         SizedBox(height: 10),
//         Text('巡检项情况:',
//             style: TextStyle(
//               fontWeight: FontWeight.bold,
//               fontSize: 16,
//               color: Colors.blue[800],
//             )),
//         SizedBox(height: 8),
//         if (spare3 != null)
//           Container(
//             decoration: BoxDecoration(
//               border: Border.all(color: Colors.grey[300]!),
//               borderRadius: BorderRadius.circular(8),
//             ),
//             child: ListView.separated(
//               physics: NeverScrollableScrollPhysics(),
//               shrinkWrap: true,
//               itemCount: spare3.length,
//               separatorBuilder: (context, index) =>
//                   Divider(height: 1, color: Colors.grey[200]),
//               itemBuilder: (context, index) {
//                 final entry = spare3!.entries.elementAt(index);
//                 return _buildInspectionItem(
//                   entry.key,
//                   entry.value,
//                   isEditable: false,
//                 );
//               },
//             ),
//           )
//         else
//           Text('暂无巡检项情况', style: TextStyle(color: Colors.grey)),
//       ],
//     );
//   }

//   Widget _buildInspectionItem(String title, String status,
//       {bool isEditable = false}) {
//     return Padding(
//       padding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
//       child: Row(
//         children: [
//           Expanded(
//             child: Text(
//               title,
//               style: TextStyle(
//                 fontSize: 15,
//                 fontWeight: FontWeight.w500,
//               ),
//             ),
//           ),
//           SizedBox(width: 10),
//           Container(
//             padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
//             decoration: BoxDecoration(
//               color: status == '正常' ? Colors.green[50] : Colors.red[50],
//               borderRadius: BorderRadius.circular(16),
//               border: Border.all(
//                 color: status == '正常' ? Colors.green : Colors.red,
//                 width: 1,
//               ),
//             ),
//             child: Text(
//               status,
//               style: TextStyle(
//                 color: status == '正常' ? Colors.green : Colors.red,
//                 fontWeight: FontWeight.bold,
//               ),
//             ),
//           ),
//         ],
//       ),
//     );
//   }

//   Widget _buildInfoRow(String label, String value) {
//     return Padding(
//       padding: EdgeInsets.symmetric(vertical: 6),
//       child: Row(
//         crossAxisAlignment: CrossAxisAlignment.start,
//         children: [
//           SizedBox(
//             width: 100,
//             child: Text(
//               '$label:',
//               style: TextStyle(
//                 fontWeight: FontWeight.bold,
//                 color: Colors.grey[700],
//               ),
//             ),
//           ),
//           SizedBox(width: 10),
//           Expanded(
//             child: SelectableText(
//               value,
//               style: TextStyle(color: Colors.grey[800]),
//             ),
//           ),
//         ],
//       ),
//     );
//   }

//   String _getPatrolMarkText(dynamic mark) {
//     switch (mark.toString()) {
//       case '1':
//         return '已巡检';
//       case '2':
//         return '未巡检';
//       default:
//         return '未知状态';
//     }
//   }

//   String _getPatrolStatusText(dynamic status) {
//     switch (status.toString()) {
//       case '1':
//         return '正常';
//       case '2':
//         return '维修';
//       case '3':
//         return '超时';
//       default:
//         return '未知状态';
//     }
//   }
// }

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';

class PointInfoDialog extends StatelessWidget {
  final dynamic content;
  final String patrolMark;

  const PointInfoDialog({
    Key? key,
    required this.content,
    required this.patrolMark,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (content == null) {
      return AlertDialog(
        title: const Text('提示'),
        content: const Text('该巡检点暂未分配任务'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      );
    }
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 40),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      elevation: 10,
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.8,
        ),
        child: Container(
          padding: EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // Title and close button
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '巡检点详情',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue[800],
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.close, color: Colors.grey),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                ],
              ),
              Divider(height: 20, thickness: 1),
              SizedBox(height: 10),

              // Scrollable content area
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // Display different content based on patrolMark
                      if (patrolMark == '1') _buildMark1Content(), //已巡
                      if (patrolMark == '2') _buildMark2Content(), //未巡检
                      if (patrolMark == '4') _buildMark4Content(), //异常
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMark1Content() {
    Map<String, dynamic>? patrolContents;
    try {
      if (content['patrolContents'] != null) {
        patrolContents =
            Map<String, dynamic>.from(json.decode(content['patrolContents']));
      }
    } catch (e) {
      print('解析 patrolContents 失败: $e');
    }

    List<String> images = [];
    if (content['images'] != null && content['images'] is List) {
      images = List<String>.from(content['images']);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildInfoRow('巡检状态', _getPatrolMarkText(content['patrolMark'])),
        _buildInfoRow('巡查状态', _getPatrolStatusText(content['patrolStatus'])),
        _buildInfoRow('实际巡查时间', content['patrolTime'] ?? '暂无'),
        _buildInfoRow('巡检任务名称', content['patrolSchemeName'] ?? '暂无'),
        _buildInfoRow('任务开始日期', content['patrolStartData'] ?? '暂无'),
        _buildInfoRow('任务结束日期', content['patrolEndData'] ?? '暂无'),
        _buildInfoRow('巡检项名称', content['patrolItemName'] ?? '暂无'),
        _buildInfoRow('实际巡检人', content['patrolUserName'] ?? '暂无实际巡检人'),

        // Inspection images section
        if (images.isNotEmpty) ...[
          SizedBox(height: 10),
          Text('巡检图片:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
                color: Colors.blue[800],
              )),
          SizedBox(height: 8),
          _buildImageGallery(images),
        ],

        SizedBox(height: 10),
        Text('巡检内容:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
              color: Colors.blue[800],
            )),
        SizedBox(height: 8),
        if (patrolContents != null)
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListView.separated(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: patrolContents.length,
              separatorBuilder: (context, index) =>
                  Divider(height: 1, color: Colors.grey[200]),
              itemBuilder: (context, index) {
                final entry = patrolContents!.entries.elementAt(index);
                return _buildInspectionItem(
                  entry.key,
                  entry.value,
                  isEditable: false,
                );
              },
            ),
          )
        else
          Text('暂无巡检内容', style: TextStyle(color: Colors.grey)),
      ],
    );
  }

  Widget _buildMark2Content() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildInfoRow('巡检状态', _getPatrolMarkText(content['patrolMark'])),
        _buildInfoRow('巡检任务名称', content['patrolSchemeName'] ?? '暂无'),
        _buildInfoRow('任务开始日期', content['patrolStartData'] ?? '暂无'),
        _buildInfoRow('任务结束日期', content['patrolEndData'] ?? '暂无'),
        _buildInfoRow('巡检项名称', content['patrolItemName'] ?? '暂无'),
        _buildInfoRow(
            '巡检人',
            (content['userName'] as List<dynamic>?)
                    ?.map((e) => e['nickName'])
                    .join('、') ??
                '暂无'),
        _buildInfoRow('巡检内容', content['patrolContents'] ?? '暂无'),
      ],
    );
  }

  Widget _buildMark4Content() {
    Map<String, dynamic>? spare3;
    try {
      if (content['spare3'] != null) {
        spare3 = Map<String, dynamic>.from(json.decode(content['spare3']));
      }
    } catch (e) {
      print('解析 patrolContents 失败: $e');
    }

    List<String> imageUrls = [];
    if (content['imageUrl'] != null && content['imageUrl'] is List) {
      imageUrls = List<String>.from(content['imageUrl']);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildInfoRow('巡检时间', content['createTime'] ?? '暂无'),
        _buildInfoRow('人员', content['registerUser'] ?? '暂无'),
        _buildInfoRow('描述', content['remark'] ?? '暂无描述'),

        // Inspection images section
        if (imageUrls.isNotEmpty) ...[
          SizedBox(height: 10),
          Text('巡检图片:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
                color: Colors.blue[800],
              )),
          SizedBox(height: 8),
          _buildImageGallery(imageUrls),
        ],

        SizedBox(height: 10),
        Text('巡检项情况:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
              color: Colors.blue[800],
            )),
        SizedBox(height: 8),
        if (spare3 != null)
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListView.separated(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: spare3.length,
              separatorBuilder: (context, index) =>
                  Divider(height: 1, color: Colors.grey[200]),
              itemBuilder: (context, index) {
                final entry = spare3!.entries.elementAt(index);
                return _buildInspectionItem(
                  entry.key,
                  entry.value,
                  isEditable: false,
                );
              },
            ),
          )
        else
          Text('暂无巡检项情况', style: TextStyle(color: Colors.grey)),
      ],
    );
  }

  Widget _buildImageGallery(List<String> imageUrls) {
    return Container(
      height: 100,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: imageUrls.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: EdgeInsets.only(right: 10),
            child: GestureDetector(
              onTap: () => _showImageDialog(context, imageUrls[index]),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Container(
                  width: 120,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Stack(
                    children: [
                      Image.network(
                        imageUrls[index],
                        width: 120,
                        height: 100,
                        fit: BoxFit.cover,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return Center(
                            child: CircularProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ),
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[200],
                            child: Center(
                              child:
                                  Icon(Icons.broken_image, color: Colors.grey),
                            ),
                          );
                        },
                      ),
                      Positioned(
                        bottom: 0,
                        right: 0,
                        child: Container(
                          padding: EdgeInsets.all(4),
                          decoration: BoxDecoration(
                            color: Colors.black54,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(8),
                            ),
                          ),
                          child: Text(
                            '${index + 1}/${imageUrls.length}',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  void _showImageDialog(BuildContext context, String imageUrl) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.all(20),
        child: Stack(
          alignment: Alignment.topRight,
          children: [
            InteractiveViewer(
              panEnabled: true,
              minScale: 0.5,
              maxScale: 3,
              child: Image.network(
                imageUrl,
                fit: BoxFit.contain,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Center(
                    child: CircularProgressIndicator(
                      value: loadingProgress.expectedTotalBytes != null
                          ? loadingProgress.cumulativeBytesLoaded /
                              loadingProgress.expectedTotalBytes!
                          : null,
                    ),
                  );
                },
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[200],
                    child: Center(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.broken_image,
                              size: 50, color: Colors.grey),
                          SizedBox(height: 10),
                          Text('图片加载失败', style: TextStyle(color: Colors.grey)),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            IconButton(
              icon: Icon(Icons.close, color: Colors.white, size: 30),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInspectionItem(String title, String status,
      {bool isEditable = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      child: Row(
        children: [
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          SizedBox(width: 10),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: status == '正常' ? Colors.green[50] : Colors.red[50],
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: status == '正常' ? Colors.green : Colors.red,
                width: 1,
              ),
            ),
            child: Text(
              status,
              style: TextStyle(
                color: status == '正常' ? Colors.green : Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey[700],
              ),
            ),
          ),
          SizedBox(width: 10),
          Expanded(
            child: SelectableText(
              value,
              style: TextStyle(color: Colors.grey[800]),
            ),
          ),
        ],
      ),
    );
  }

  String _getPatrolMarkText(dynamic mark) {
    switch (mark.toString()) {
      case '1':
        return '已巡检';
      case '2':
        return '未巡检';
      default:
        return '未知状态';
    }
  }

  String _getPatrolStatusText(dynamic status) {
    switch (status.toString()) {
      case '1':
        return '正常';
      case '2':
        return '故障（已维修）';
      case '3':
        return '超时';
      default:
        return '未知状态';
    }
  }
}
